/*
* This file is part of RoboDS (http://code.google.com/p/robods/)
* Copyright (C) 2007 Blakharaz
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/

#include "DsMoveRobotsState.h"

#include "DsGame.h"
#include "JobQueue.h"
#include "Logger.h"
#include "RobotController.h"

namespace robo
{

    DsMoveRobotsState::DsMoveRobotsState(DsGame* game)
    : MoveRobotsState(game)
    {
    }

    DsMoveRobotsState::~DsMoveRobotsState()
    {
    }

    void DsMoveRobotsState::resume()
    {
	    mCurrentRobot = BEFORE_FIRST_ROBOT;
    }

    void DsMoveRobotsState::handleEvents()
    {
	    static MovementTurnMap robotTurns;
	    static JobQueue* currentQueue = new JobQueue();

	    if (mCurrentCard > 4) // Last card has been executed before -> start a new rount
	    {
		    mCurrentCard = 0;
		    switchGameState(GameState::PREPARE_ROUND);
		    return;
	    }

	    if (!currentQueue->isEmpty())
	    {
		    currentQueue->advanceOneFrame();
	    }
	    else
	    {
		    if (mCurrentRobot + 1 >= mControllers.size())
		    {
			    Logger::getSingleton()->log("Movement done, switch to board effects");
			    mCurrentCard++;
			    switchGameState(GameState::BOARD_EFFECTS);
			    return;
		    }

		    Logger::getSingleton()->log("empty rob %d", mCurrentRobot);
		    if (mCurrentRobot == BEFORE_FIRST_ROBOT)
		    {
			    robotTurns.clear();
			    for (std::vector<RobotController*>::const_iterator 
				    it = mControllers.begin(); it != mControllers.end(); ++it)
			    {
				    RobotController* cur = *it;
				    robotTurns[cur->getActiveCard(mCurrentCard)] = cur->getRobot();
			    }
		    }

		    mCurrentRobot++;
    				
		    MovementTurnMap::iterator curRobIt = robotTurns.begin();
		    for (unsigned short idx = 0; idx < mCurrentRobot; ++idx)
		    {
			    ++curRobIt;
		    }

		    Card* curCard = curRobIt->first;
		    Robot* curRobot = curRobIt->second;

		    calculateJobs(curRobot, curCard, currentQueue);

		    ///@todo trigger instant effects (e.g. pit -> death)
	    }
    }

}
